#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
import wx
import base64
# 需要安装 wxPython


class MyApp(wx.Frame):
    def __init__(self, parent, title):
        super(MyApp, self).__init__(parent, title=title, size=(640, 480))
        panel = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        # head
        boxHead = wx.BoxSizer(wx.HORIZONTAL)
        staticHead = wx.StaticText(panel, -1, "BASE64固定头")
        boxHead.Add(staticHead, 1, wx.ALIGN_LEFT | wx.ALL, 5)
        self.areahead = wx.TextCtrl(panel, size=(500, 22), style= wx.TE_RICH)
        boxHead.Add(self.areahead, 1, wx.ALIGN_LEFT | wx.ALL, 5)
        vbox.Add(boxHead)
        self.areahead.SetValue('base64://')

        # cipher
        boxCipher = wx.BoxSizer(wx.HORIZONTAL)
        # staticCipher = wx.StaticText(panel, -1, "密文")
        # boxCipher.Add(staticCipher, 1, wx.ALIGN_LEFT | wx.ALL, 5)

        self.btncipher = wx.Button(panel, -1, "解密")
        boxCipher.Add(self.btncipher, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)
        self.btncipher.Bind(wx.EVT_BUTTON, self.OnEnterCipher)

        self.areaCipher = wx.TextCtrl(panel, size=(500, 200), style=wx.TE_MULTILINE | wx.TE_RICH)
        boxCipher.Add(self.areaCipher, 1, wx.ALIGN_LEFT | wx.ALL, 5)

        vbox.Add(boxCipher)

        # Plaintext
        boxPlaintext = wx.BoxSizer(wx.HORIZONTAL)
        # staticPlaintext = wx.StaticText(panel, -1, "明文")
        # boxPlaintext.Add(staticPlaintext, 1, wx.ALIGN_LEFT | wx.ALL, 5)

        self.btnPlaintext = wx.Button(panel, -1, "加密")
        boxPlaintext.Add(self.btnPlaintext, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)
        self.btnPlaintext.Bind(wx.EVT_BUTTON, self.OnEnterPlaintext)

        self.areaPlaintext = wx.TextCtrl(panel, size=(500, 200), style=wx.TE_MULTILINE | wx.TE_RICH)
        boxPlaintext.Add(self.areaPlaintext, 1, wx.ALIGN_LEFT | wx.ALL, 5)

        vbox.Add(boxPlaintext)

        panel.SetSizer(vbox)
        self.Centre()
        self.Show()
        self.Fit()

    def OnEnterCipher(self, event):
        # clear
        self.areaPlaintext.SetValue('')
        # head
        hv = self.areahead.GetValue()
        c = self.areaCipher.GetValue()
        if hv:
            if hv == c[:len(hv)]:
                c = c[len(hv):]
        # decode
        p = base64.b64decode(c)
        p = p.decode()
        self.areaPlaintext.SetValue(p)
        print(p)

    def OnEnterPlaintext(self, event):
        # clear
        self.areaCipher.SetValue('')
        p = self.areaPlaintext.GetValue()
        # encode
        c = base64.b64encode(p.encode('utf-8'))
        # head
        hv = self.areahead.GetValue()
        if hv:
            c = hv + c.decode()
        self.areaCipher.SetValue(c)
        print(c)


if __name__ == "__main__":
    app = wx.App()
    MyApp(None, 'Base64')
    app.MainLoop()
